package com.doyens.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doyens.reggie.domain.Category;
import com.doyens.reggie.domain.Dish;
import com.doyens.reggie.domain.DishFlavor;
import com.doyens.reggie.dto.DishDto;
import com.doyens.reggie.mapper.CategoryMapper;
import com.doyens.reggie.mapper.DishMapper;
import com.doyens.reggie.service.CategoryService;
import com.doyens.reggie.service.DishFlavorService;
import com.doyens.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    public void saveDishAndFlavor(DishDto dishDto) { //{id=null,name=麻辣兔头，price=85000}
        // 先添加菜品表dish
        this.save(dishDto); //mybatisplus会将自动生成的id赋值给对象的主键字段 //{id=56,name=麻辣兔头，price=85000}

        Long dishId = dishDto.getId(); //56
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishId);
        }
        // 再添加到口味表dish_flavor
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public void delDishAndFlavor(Long[] ids) {
        for (Long id : ids) {
            // 先删除口味表
            dishFlavorService.remove(new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId,id));

            // 再删除菜品表
            this.removeById(id);
        }
    }

    @Override
    public void updateStatus(int status, Long[] ids) {
        for (Long id : ids) {
            Dish dish = new Dish();
            dish.setId(id);
            dish.setStatus(status);
            this.updateById(dish);//底层是动态sql
        }
    }

    @Override
    public void updateDish(DishDto dishDto) {
        // 先修改菜品表
        this.updateById(dishDto);
        // 对于口味表来说 先删除老数据 再添加的新的数据
        dishFlavorService.remove(new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId,dishDto.getId()));

        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavors);
    }
}
